package com.webserver.core;

import com.webserver.controllers.UserController;
import com.webserver.http.HttpContext;
import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class DispatcherServlet {
    /*
    * V16版本的第一个改动，不再使用url作为请求路径了，
    * 因为若提交数据，url中会包含？
    * */
    public void service(HttpRequest request,HttpResponse response) throws IOException {
        String path = request.getRequestURL();

        //首先判断请求路径是否为请求业务
        if("/myweb/regUser".equals(path)){//是否为用户注册
            UserController controller = new UserController();
            controller.reg(request,response);
        }else {
            File file = new File("./webapps" + path);
//        String postfix = path.substring(path.lastIndexOf(".")+1);
//        Map<String,String> type = new HashMap<>();
//        type.put("html","text/html");
//        type.put("css","text/css");
//        type.put("js","application/javascript");
//        type.put("png","image/png");
//        type.put("gif","image/gif");
//        type.put("jpg","image/jpeg");
//        String value = type.get(postfix);
//        String postfix = file.getCanonicalPath();
            if (file.exists() && file.isFile()) {
                response.setEntily(file);
                //资源存在
            } else {
                ;            //资源不存在
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                file = new File("./webapps/root/404.html");
                response.setEntily(file);
            }
        }
        response.addHeader("Server","WebServer");
    }
}
